//
//  DDLoginView.swift
//  swift微博
//
//  Created by whitcast on 16/7/10.
//  Copyright © 2016年 whitcast. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

//appkey
var client_id : String = "755405151"
//回调地址
var redirect_uri :String = "http://www.itcast.com"
//appsecret
var  weiboAppSecret : String = "961ecb0b687358e18133b5173a1a4c7a"
//初始请求code的url
var urlNor :String?


class DDLoginVC: UIViewController,UIWebViewDelegate {
    
    private lazy var webViews = UIWebView()
    
    override func loadView() {
        super.loadView()
        
        webViews.delegate = self
        //取消webView上拉的黑条,取消不透明
        webViews.opaque = false
        
        view = webViews
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor(white: 237.0/255.0, alpha: 1)
        
        setUpUI()
        //加载授权网页
        setWebView()
        
        
    }
    //https://api.weibo.com/oauth2/authorize?client_id=755405151&redirect_uri=http://www.itcast.com
    // MARK:--设置UIWebView
    func setWebView(){
        //url
        urlNor = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        let request = NSURLRequest(URL: NSURL(string: urlNor!)!)
        
        webViews.loadRequest(request)
        
        
    }
    
    //设置UI
    func setUpUI() {
        //返回按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "返回", style: .Plain, target: self, action: "back")
        //自动填充按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "自动填充", style: .Plain, target: self, action: "autoFillNmae")
        //标题
        navigationItem.title = "登录"
        
    }
    
    func back() {
        //删除弹窗
        SVProgressHUD.dismiss()
        //销毁控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
    //自动填充用户名和密码
    func autoFillNmae() {
        //修改javascript 的标签值
        webViews.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '18717891741'; document.getElementById('passwd').value = '405864'")
        
    }
    
    // MARK: --webView的代理方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //取得code()
        guard let url:NSURL? = request.URL else {
            return false
        }
        
        if ((url?.absoluteString.hasPrefix(redirect_uri)) == false) {
            return true
        }
        
 //        // MARK: ---获取code,授权码
        //授权页面,确定和取消唯一的不同是url后面的query
        guard let querl = url!.query where querl.hasPrefix("code=") else{
            //销毁控制器
            self.dismissViewControllerAnimated(true, completion: nil)
            
            return false

        }
        
        let code = querl.substringFromIndex("code=".endIndex)
        //获取appToken
        getAppTokens(code)
        
           return false //防止回调页出现
        
    }
    
    
    func webViewDidStartLoad(webView: UIWebView){
        //显示正在加载的图
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView){
        //销毁弹窗
        SVProgressHUD.dismiss()
        
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?){
        //销毁弹窗
        SVProgressHUD.dismiss()
        
        print(error)
        
    }
    
    func getAppTokens(code :String) {
        //根据授权码获取apptoken.并取得用户数据
        DDOAuthViewModel.shardOAuthVM.getApptoken(code) { (isSuccess) -> () in
            if isSuccess {
                print("获取用户数据成功")
                //发送通知
                NSNotificationCenter.defaultCenter().postNotificationName("changeVC", object: self, userInfo: nil)
                
            }else {
                print("获取用户数据失败")
            }
        }
    }
}

















